<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Website_model extends CI_Model {

	public $websites_tbl = 'websites';
	public $userweb_tbl = 'user_websites';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	// ------------------------------------------------------------------------
	
	public function list_websites()
	{
		$query = $this->db->where('deleted', 'n')
						  ->order_by('site_name')
						  ->get('websites');
						  
		return $query->num_rows() > 0 ? $query->result_array() : FALSE;
	}
	
	// ------------------------------------------------------------------------
	
	public function create_user_websites($fields, $user_id)
	{
		foreach ($fields as $website)
		{
			$data[] = array(
				'site_code'		=> $website,
				'user_id'		=> $user_id
			);
		}
		
		if (! $data) return TRUE;
		
		return $this->db->insert_batch('user_websites', $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function update_user_websites($fields, $user_id)
	{
		$query = $this->db->where('user_id', $user_id)
						  ->delete('user_websites');
						  
		return $this->create_user_websites($fields, $user_id);
	}
	
	// ------------------------------------------------------------------------
	
	public function list_user_websites($user)
	{
		$query = $this->db->join($this->websites_tbl . ' AS w', 'w.site_code = uw.site_code', 'left')
						  ->where('uw.user_id', $user['user_id'])
						  ->where('w.deleted', 'n')
						  ->order_by('site_name')
						  ->get($this->userweb_tbl . ' AS uw');
						  
		return $query->num_rows() > 0 ? $query->result_array() : FALSE;				  
	}
	
	// ------------------------------------------------------------------------
	
	public function get_user_websites($user)
	{
		$query = $this->db->select('GROUP_CONCAT(site_code) AS sites')
						  ->where('user_id', $user['user_id'])
						  ->get($this->userweb_tbl, 1);
						  
		return $query->num_rows() > 0 ? $query->row_array() : FALSE;
	}
	
	// ------------------------------------------------------------------------
}

/* End of file website_model.php */
/* Location: ./application/models/website_model.php */